// SlagCar/WaybillCancelApplyDetl/WaybillCancelApplyDetl.js
import {config} from "../../utils/config";
import {imgCompress} from "../../utils/img";

const req = require('../../utils/request');
Page(  {

  /**
   * 页面的初始数据
   */
  data: {
    system_id: wx.getStorageSync('system_id') || 1164,  //231215 yan 图片字段只返回文件名时，需要系统号拼接图片地址
    baseURL: req.baseURL,

    rowData: {},



    validFlag: false,             // 验证标识
    validObj: {},                 // 验证表单项


    // 取消运单申请
    cancelShow: false,
    agree: true,
    cancelField: [
      {field_id: 'reason',label: '原因',type: 'textarea',is_null: true},
    ],
    cancelData: {},


    cancelUserList: null

  },

  /**
   * 初始获取运单信息
   * 1、填充运单信息
   * 2、判断运单状态
   * 3、根据运单状态显示不同按钮、弹窗标题，设置弹窗字段项
   */
  getRowData(){
    return new Promise(resolve => {
      let url = 'DynamicQuery/query_dynamic_v2',
        {row_id} = this.data,
        post = {row_id,table_id: 'muck_waybill_main'};
      wx.showLoading({mask: true})
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        wx.hideLoading();
        let data = res.data.row && res.data.row[0];
        if (data){
          let driver_row_id = wx.getStorageSync('driver_row_id');
          let rowData = data.entity[0],
            //判断运单状态：1、当前登录司机为当前订单指派人员 2、开始时间为空则未开始（0）  3、开始时间不为空结束时间为空:已开始（1） 4、开始时间结束时间不为空: 已结束（2）
            status = driver_row_id == rowData.reference1_driver ? (rowData.driver_start_time && rowData.driver_end_time ? 2 : rowData.driver_start_time ? 1 : 0) : 3

          this.setData({rowData,inputData: {},status});

        }
        resolve();
      })

    })
  },
  // 同意取消
  agreeCancel(){
    this.setData({agree: true,cancelShow: true})

  },
  // 拒绝取消
  refuseCancel(){
    this.setData({agree: false,cancelShow: true})

  },
  bindAuditCancel(){
    let {row_id,agree,cancelData} = this.data,
      url = 'ZTAuth/AuditCancelWaybill',
      post = {
        row_id,
        agree,
        ...cancelData
      };
    wx.$post(5,url,post).then(res =>{
      if (res.errcode != 0) return
      this.setData({cancelShow: false});
      wx.$toast('提交成功')
      this.getRowData();
    })
  },

  bindAuditChange(e){
    let {field,val,optItem} = e.detail,
      id = field.field_id || field.fieldName;

    //赋值
    this.data.cancelData[id] = val
  },

  bindClose(){
    this.setData({show:false,showPicker: false,showDest: false,cancelShow: false})
  },





  // 记录验证表单项
  validIpt(e) {
    let { validObj, } = this.data
    this.data.validObj = {
      ...validObj,
      ...e.detail,
    };
  },
  //验证数据
  validForm(validObj){
    return new Promise((resolve, reject) => {
      let valid = Object.values(validObj).includes(false,) ? false : true;
      resolve(valid)
    })
  },

  //判断必填项 data:数据项，required必填项对象
  checkRequired(data,required){
    let flag = true;
    Object.keys(required).forEach(item => {
      let value = data[item]
      if (flag && ['',undefined,null].includes(value)){
        wx.$toast(required[item]);
        flag = false;
      }
    })
    return flag;
  },

  //预览照片
  previewImg(e){
    let {list,i} = e.currentTarget.dataset;
    list = list && list.split(',') || []
    let {  system_id,baseURL } = this.data,
      imgs = [];
    //231221 yan 修改 图片字段只返回文件名称，通过系统号拼接图片访问地址
    list.forEach(item => {
      let name = item.substring(item.lastIndexOf('/')+1);
      imgs.push(`${baseURL}/files/${system_id}/${name}`)
    });
    //231221 end
    wx.previewImage({
      current: imgs[i],
      urls: imgs
    })
  },



  // 获取审批取消运单人员
  getCancelUser(){
    return new Promise(resolve => {
      if (this.data.cancelUserList){
        resolve(this.data.cancelUserList);
        return
      }
      wx.showLoading({mask: true});
      wx.$get(5,'ZTAuth/AuditCancelWaybillUser').then(res =>{
        wx.hideLoading();
        if (res.errcode != 0) return;
        let data = res.data.row || [];
        this.data.cancelUserList = data;
        resolve(data);
      })
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let {row_id} = options;
    this.data.row_id = row_id;
    this.getRowData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.getSetting({
      success(res){
        if (!res.authSetting['scope.userLocation']){
          console.log('未打开定位服务');
          wx.getLocation({
            type: 'gcj02', // 比较精确
            success: (res) => {
              console.log(res);
            },
            fail: (res) =>{
              wx.showModal({
                title: '定位服务未打开',
                content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                confirmText: '去开启',
                success: (res) => {
                  if(res.confirm) {
                    wx.openSetting();
                  }
                },
              });
            }
          })

        }else {
          const systemSetting = wx.getSystemSetting();
          if (systemSetting.locationEnabled === false) {
            wx.showModal({
              title: '定位服务未打开',
              content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
              confirmText: '确定',
              showCancel: false,
              success: (res) => {
                if(res.confirm) {
                  wx.navigateTo({url:'/SlagCar/OpenLocationGuide/OpenLocationGuide'})
                }
              },
            })
          }
        }

      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
